package whisper.api.gateway.frame.auth.filter.permission;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import whisper.api.gateway.frame.auth.domain.Role;
import whisper.api.gateway.frame.auth.domain.User;
import whisper.api.gateway.frame.auth.service.RoleService;
import whisper.api.gateway.frame.auth.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by JT on 2017/9/22.
 */
@Service
public class LightSwordUserDetailService  implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /**
         * 通过用户名加载用户
         */
        User user = null;
        try {
            user = userService.findUserByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("用户不存在！");
        }

        List<Role> roles = roleService.findRolesByUserId(user.getId());
        List<GrantedAuthority> authentications = new ArrayList<>();
        for (Role role : roles) {
            authentications.add(new SimpleGrantedAuthority(role.getCode()));
        }

        boolean enable = user.getIsAvailable() == 1;
        boolean accountNonExpired = user.getIsOverdue() == 1;
        boolean accountNonLocked = user.getIsLock() == 1;

        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), enable,
                accountNonExpired, true, accountNonLocked, authentications);
    }
}
